package com.hkbigdata.sybx.controller;

import com.hkbigdata.sybx.bean.OrderInfo;
import com.hkbigdata.sybx.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liuanbo
 * @creat 2025-06-04-18:08
 * @see 2194550857@qq.com
 */
@RestController
@CrossOrigin
@RequestMapping("/api/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 创建订单
     */
    @PostMapping("/create")
    public Map<String, Object> createOrder(@RequestBody OrderInfo orderInfo) {
        Map<String, Object> result = new HashMap<>();

        try {
            int createResult = orderService.createOrder(orderInfo);
            if (createResult > 0) {
                result.put("code", 200);
                result.put("message", "订单创建成功");
                result.put("orderNo", orderInfo.getOrderNo());
            } else {
                result.put("code", 500);
                result.put("message", "订单创建失败");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "订单创建失败：" + e.getMessage());
            System.err.println("订单创建失败：" + e.getMessage());
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 根据用户ID获取订单列表
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<?> getOrderList(@PathVariable String userId) {
        try {
            if (userId == null || userId.trim().isEmpty()) {
                Map<String, Object> errorMap = new HashMap<>();
                errorMap.put("code", 400);
                errorMap.put("message", "用户ID不能为空");
                return ResponseEntity.badRequest().body(errorMap);
            }

            List<OrderInfo> orders = orderService.getOrdersByUserId(userId);
            if (orders == null) {
                return ResponseEntity.ok(Collections.emptyList());
            }

            System.out.println("用户订单信息：" + orders);
            return ResponseEntity.ok(orders);

        } catch (Exception e) {
            System.err.println("获取用户订单失败：" + e.getMessage());
            e.printStackTrace();

            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("code", 500);
            errorMap.put("message", "获取订单失败，请稍后重试");

            return ResponseEntity.status(500).body(errorMap);
        }
    }

    /**
     * 获取所有订单（后台管理）
     */
    @GetMapping("/all")
    public List<OrderInfo> getAllOrders() {
        System.out.println("后台订单信息：" + orderService.getAllOrders());
        return orderService.getAllOrders();
    }

    /**
     * 根据订单号获取订单详情
     */
    @GetMapping("/detail/{orderNo}")
    public ResponseEntity<?> getOrderDetail(@PathVariable String orderNo) {
        try {
            OrderInfo order = orderService.getOrderByNo(orderNo);
            if (order != null) {
                return ResponseEntity.ok(order);
            } else {
                Map<String, Object> errorMap = new HashMap<>();
                errorMap.put("code", 404);
                errorMap.put("message", "订单不存在");
                return ResponseEntity.status(404).body(errorMap);
            }
        } catch (Exception e) {
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("code", 500);
            errorMap.put("message", "获取订单详情失败");
            return ResponseEntity.status(500).body(errorMap);
        }
    }

    /**
     * 删除订单
     */
    @DeleteMapping("/delete/{orderNo}")
    public Map<String, Object> deleteOrder(@PathVariable String orderNo) {
        boolean success = orderService.deleteOrder(orderNo);
        Map<String, Object> response = new HashMap<>();
        response.put("success", success);
        response.put("message", success ? "订单删除成功" : "订单删除失败");
        return response;
    }

    /**
     * 更新订单信息
     */
    @PutMapping("/update")
    public Map<String, Object> updateOrder(@RequestBody OrderInfo order) {
        boolean success = orderService.updateOrder(order);
        Map<String, Object> response = new HashMap<>();
        response.put("success", success);
        response.put("message", success ? "订单更新成功" : "订单更新失败");
        return response;
    }

    /**
     * 更新订单状态
     */
    @PutMapping("/status")
    public Map<String, Object> updateOrderStatus(@RequestParam String orderNo, @RequestParam Integer orderStatus) {
        boolean success = orderService.updateOrderStatus(orderNo, orderStatus);
        Map<String, Object> response = new HashMap<>();
        response.put("success", success);
        response.put("message", success ? "订单状态更新成功" : "订单状态更新失败");
        return response;
    }
}

